<template>
	<view class="index">
	</view>
</template>

<script>
	import {
		ethers
	} from "ethers";
	export default {
		data() {
			return {
				ref: '',
				signer: null,
			}
		},
		async onLoad(option) {
			uni.showLoading({});
			this.ref = option.ref ? option.ref : '';
			if (this.ref) {
				uni.setStorageSync('ref', this.ref);
			}
			if (typeof window.ethereum !== "undefined") {
				let web3 = new ethers.providers.Web3Provider(window.ethereum)
				setTimeout(() => {
					window.ethereum.enable(); // get permission to access accounts
					this.signer = web3.getSigner()
					this.signer.getAddress().then((account) => {
						console.log('初始化erc20');
						this.$store.commit("setAddress", account)
						uni.setStorageSync('address', account);
						this.login()
					}).catch((err) => {
						console.log(err)
					});
				}, 300)
			} else {
				this.$toast(this.$t('请先安装') + '：MetaMask')
			}
		},
		methods: {
			async login() {
				console.log('调登录接口了');
				this.$http.get('/api/auth/is_login').then(res => {
					if (res.code == 200) {
						if (res.data.is_login) {
							this.$go(4, '/pages/index/index'); // 已登陆
						} else {
							this.getLogin(); // 未登录
						}
					}
				})
			},
			async getLogin() {
				let timestamp = Date.parse(new Date()) / 1000;
				this.signer.signMessage('Login-' + timestamp).then(signer => {
					console.log('当前登录钱包地址：', this.$store.state.address);
					console.log('签名数据：', signer);
					this.$http.post('/api/auth/login', {
						address: this.$store.state.address || uni.getStorageSync('address'),
						signature: signer,
						timestamp: timestamp,
						ref: this.ref ? this.ref : uni.getStorageSync('ref')
					}).then(res => {
						uni.hideLoading();
						if (res.code == 200) {
							uni.setStorageSync('token', res.data.token);
							this.$go(4, '/pages/index/index?ref=' + this.ref)
						}
					})
				}).catch(err => {
					this.$toast(err.message)
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.index {
		height: 1624rpx;
		// background: url('../../static/img/login.png')no-repeat left top;
		// background-size: 750rpx 1624rpx;
	}
</style>